<template>
  <div>
    <page>
      <div slot="aside">
        <el-tabs type="card">
          <div class="cover-all"></div>
          <el-tab-pane label="组织机构">
            <unitTree :width="'100%'" @click="handleInUnitClick"></unitTree>
            <!-- <out-unit-tree :width="'100%'" @click="handleOutUnitClick"></out-unit-tree> -->
          </el-tab-pane>
        </el-tabs>
      </div>
      <!--工具栏-->
      <div slot="toolbar">
        <el-form :inline="true" :model="filters">
          <el-form-item>
            <el-input
              v-model="filters.name"
              placeholder="角色名"
              clearable
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="btnSearch">
        <el-button @click="handleQuery('a')">查询</el-button>
        <el-button
          type="primary"
          @click="handleAdd"
          v-show="hasPerm('sys:role:add')"
          >新增</el-button
        >
      </div>
      <!--表格内容栏-->
      <div slot="content">
        <el-table
          :header-cell-style="{ background: '#e7eaf0', color: '#606266' }"
          :data="pageResult"
          stripe
          style="width: 100%"
          rowKey="id"
          v-loading="loading"
          element-loading-text="加载中..."
        >
          <!-- <el-table-column prop="id" header-align="center" align="center" width="80" label="ID"></el-table-column> -->
          <table-tree-column
            prop="name"
            header-align="center"
            treeKey="id"
            align="center"
            label="角色名称"
          ></table-tree-column>

          <el-table-column
            prop="groupName"
            header-align="center"
            align="center"
            label="所属机构"
          ></el-table-column>
          <el-table-column
            prop="inserttime"
            header-align="center"
            align="center"
            label="创建时间"
          ></el-table-column>

          <el-table-column
            fixed="right"
            header-align="center"
            align="center"
            width="260"
            :label="$t('action.operation')"
          >
            <template slot-scope="scope">
              <el-button
                type="primary"
                @click="handleEdit(scope.row)"
                v-show="hasPerm('sys:role:edit')"
                >编辑</el-button
              >
              <el-button
                type="info"
                @click="handlePerm(scope.row)"
                v-show="hasPerm('sys:role:allot')"
                >分配权限</el-button
              >
              <el-button
                type="danger"
                @click="handleDelete(scope.row)"
                v-show="hasPerm('sys:role:remove')"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer">
        <el-pagination
          layout="total, prev, pager, next, jumper"
          @current-change="refreshPageRequest"
          :current-page="pageRequest.page"
          :page-size="pageRequest.limit"
          :total="totalSize"
          style="float: right"
        ></el-pagination>
      </div>

      <!-- <kt-table :height="220" permsEdit="sys:role:edit" permsDelete="sys:role:delete" :highlightCurrentRow="true" :stripe="false"
		:data="pageResult" :columns="columns" :showBatchDelete="false" @handleCurrentChange="handleRoleSelectChange"
		@findPage="findPage" @handleEdit="handleEdit" @handleDelete="handleDelete">
      </kt-table>-->
      <!-- </el-col> -->

      <!--角色菜单，表格树内容栏-->
      <!-- <div class="menu-container" :v-if="true">
		<div class="menu-header">
			<span><B>角色菜单授权</B></span>
		</div>
		<el-tree :data="menuData" size="mini" show-checkbox node-key="id" :props="defaultProps"
			style="width: 100%;pading-top:20px;" ref="menuTree" :render-content="renderContent"
			v-loading="menuLoading" element-loading-text="拼命加载中" :check-strictly="true"
			@check-change="handleMenuCheckChange">
		</el-tree>
		<div style="float:left;padding-left:24px;padding-top:12px;padding-bottom:4px;">
			<el-checkbox v-model="checkAll" @change="handleCheckAll" :disabled="this.selectRole.id == null"><b>全选</b></el-checkbox>
		</div>
		<div style="float:right;padding-right:15px;padding-top:4px;padding-bottom:4px;">
			<kt-button :label="$t('action.reset')" perms="sys:role:edit" type="primary" @click="resetSelection" 
				:disabled="this.selectRole.id == null"/>
			<kt-button :label="$t('action.submit')" perms="sys:role:edit" type="primary" @click="submitAuthForm" 
				:disabled="this.selectRole.id == null" :loading="authLoading"/>
		</div>
      </div>-->
    </page>
    <!--新增编辑界面-->
    <el-dialog
      :title="operation ? '新增' : '编辑'"
      width="40%"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
    >
      <el-form
        :model="dataForm"
        label-width="80px"
        :rules="dataFormRules"
        ref="dataForm"
      >
        <el-form-item label="ID" prop="id" v-if="false">
          <el-input
            v-model="dataForm.id"
            :disabled="true"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="默认角色" prop="PID" v-if="operation">
          <el-select v-model="dataForm.PID" clearable placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item._id"
              :label="item.name"
              :value="item._id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色名" prop="name">
          <el-input v-model="dataForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注 " prop="remark">
          <el-input
            v-model="dataForm.remark"
            auto-complete="off"
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click.native="submitForm"
          :loading="editLoading"
          >确定</el-button
        >
      </div>
    </el-dialog>
    <!-- 权限分配 -->
    <el-dialog title="权限分配" :visible.sync="dialogVisiblePerm" id="dialog">
      <PermPage
        v-if="dialogVisiblePerm"
        :data="dataForm"
        @handleClose="handleClose"
        @handleSave="handleQuery"
      ></PermPage>
    </el-dialog>
  </div>
</template>

<script>
import KtTable from "@/views/Core/KtTable";
import unitTree from "./comments/unitTree";
import KtButton from "@/views/Core/KtButton";
import TableTreeColumn from "@/views/Core/TableTreeColumn";
import { format } from "@/utils/datetime";
import PermPage from "./comments/PermPage";
export default {
  components: {
    unitTree,
    KtTable,
    KtButton,
    TableTreeColumn,
    PermPage,
  },
  data() {
    return {
      asideShow: false,
      loading: false,
      filters: {
        GID: "",
        name: "",
      },
      editLoading: false,
      dataFormRules: {
        name: [
          { required: true, message: "菜单名称不能为空", trigger: "blur" },
        ],
      },

      // 新增编辑界面数据
      dataForm: {
        id: 0,
        name: "",
        remark: "",
      },
      pageResult: [],
      groupDataGID: "", //选择的组ID
      pageRequest: {
        page: 1,
        limit: 10,
      },
      totalSize: 0,
      dialogVisible: false,
      operation: false,
      dialogVisiblePerm: false,
    };
  },
  methods: {
    //默认角色 val 为组件回调参数
    getUserList() {
      // 这是个函数 所以传参进去
      this.$api.role
        .defaultRole_list()
        .then((res) => {
          // then 这里是异步后台接口返回数据
          if (res.code == 0) {
            this.options = res.data; // 没定义 报错了
          }
        })
        .catch((err) => {
          // 这里是如果接口报错 或者网络不好。接口请求失败的结果 一般来说需要做处理 比如弹出警告窗提醒用户
          this.$message({
            message: "网络异常,请重试 " + res.msg,
            type: "error",
          });
        });
    },

    // 获取分页数据
    handleQuery: function (val) {
      //this.$refs.outUnitTree.handleQuery();
      this.loading = true;
      //   this.pageRequest = Object.assign(this.filters)
      let params = {
        rows: {},
        where: this.filters,
        page: val ? "" : this.pageRequest.page,
        limit: val ? "" : this.pageRequest.limit,
      };

      let param = JSON.stringify(params);
      this.$api.role.findPage(param).then((res) => {
        if (res.code == 0) {
          this.loading = false;
          this.pageResult = res.data;
          this.pageResult.map((item) => {
            item.inserttime = this.$format(item.inserttime);
          });
          this.totalSize = res.count;
        } else {
          this.$message({
            message: "网络异常,请重试 " + res.msg,
            type: "error",
          });
        }
        // this.popupTreeData = this.getParentMenuTree(res.data);
      });
    },
    refreshPageRequest(page) {
      this.pageRequest.page = page;
      this.handleQuery();
    },
    handleInUnitClick(data) {
      //   this.groupDataGID = data.GID;

      this.filters.GID = data.GID;
      //   this.pageRequest.name=data.name
      //   this.pageRequest.status = data.status;
      this.pageRequest.page = 1;
      this.handleQuery();
    },
    handlePerm(row) {
      this.dialogVisiblePerm = true;
      this.dataForm = JSON.parse(JSON.stringify(row));
    },
    // 删除
    handleDelete(data) {
      this.$confirm("确认删除选中记录吗？", "提示", {
        type: "warning",
      }).then(() => {
        // let params = this.getDeleteIds([], row);
        let params = {
          tbn: "authority_role",
          where: {
            _id: data._id,
          },
        };

        var aaa = JSON.stringify(params);
        this.$api.role.batchDelete(aaa).then((res) => {
          if (res.code == 0) {
            this.handleQuery();
            this.$message({ message: "删除成功", type: "success" });
          } else {
            this.$message({
              message: "操作失败, " + res.msg,
              type: "error",
            });
          }
        });
      });
    },
    // 显示新增界面
    handleAdd: function () {
      this.dialogVisible = true;
      this.operation = true;
      this.dataForm = {
        _id: "",
        GID: this.filters.GID,
        name: "",
        remark: "",
      };
    },
    handleClose() {
      this.dialogVisiblePerm = false;
    },
    // 显示编辑界面
    handleEdit: function (params) {
      this.dialogVisible = true;
      this.operation = false;

      this.dataForm = Object.assign({}, params);
    },
    // 编辑
    submitForm: function () {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            this.editLoading = true;
            // let params = Object.assign({}, this.dataForm);
            let params = {
              rows: this.dataForm,
              where: { _id: this.dataForm._id },
            };
            let paramJson = JSON.stringify(params);
            this.$api.role.save(paramJson).then((res) => {
              this.editLoading = false;
              if (res.code == 0) {
                this.$message({ message: "操作成功", type: "success" });
                this.dialogVisible = false;
                this.$refs["dataForm"].resetFields();
              } else {
                this.$message({
                  message: "操作失败, " + res.msg,
                  type: "error",
                });
              }
              this.handleQuery(null);
            });
          });
        }
      });
    },
    // 获取数据
    findTreeData: function () {
      this.menuLoading = true;
      this.$api.menu.findMenuTree().then((res) => {
        this.menuData = res.data;
        this.menuLoading = false;
      });
    },
    // 角色选择改变监听
    handleRoleSelectChange(val) {
      if (val == null || val.val == null) {
        return;
      }
      this.selectRole = val.val;
      this.$api.role.findRoleMenus({ roleId: val.val.id }).then((res) => {
        this.currentRoleMenus = res.data;
        this.$refs.menuTree.setCheckedNodes(res.data);
      });
    },

    // 递归全选
    checkAllMenu(menuData, allMenus) {
      menuData.forEach((menu) => {
        allMenus.push(menu);
        if (menu.children) {
          this.checkAllMenu(menu.children, allMenus);
        }
      });
    },
  },
  mounted() {
    this.handleQuery();
    //调用默认角色
    this.getUserList();
  },
};
</script>
<style less="scss" scoped>
.menu-container {
  margin-top: 10px;
}
.menu-header {
  padding-left: 8px;
  padding-bottom: 5px;
  text-align: left;
  font-size: 16px;
  color: rgb(20, 89, 121);
}
</style>